// 配置管理
import { computed, ref, watch } from "vue";
import { defaultSettings, themeList, whiteNoiseList } from "./constant.js";
import { isProduction } from "@/utils/env.js";
import { openClock, closeClock } from "./clock.js";

/**
 * 配置相关响应式数据
 */
export const settings = ref();

/**
 * 音频对象
 */
let audio = null;

/**
 * 抽屉开关状态
 */
export const isDrawerOpen = ref(false);

// 计算当前主题标签
export const currentThemeLabel = computed(() => {
  const theme = themeList.find((item) => item.name === settings.value.theme);
  return theme ? theme.label : "浅色";
});

/**
 * 是否是暗黑主题
 */
export const isDarkTheme = ref(false);

/**
 * 重置是否暗黑主题
 */
export const resetIsDarkTheme = () => {
  // 如果主题设置为"dark"
  if (settings.value.theme === "dark") {
    isDarkTheme.value = true;
    return;
  }
  // 如果主题设置为"light"
  if (settings.value.theme === "light") {
    isDarkTheme.value = false;
    return;
  }
  // 如果主题设置为"auto"
  if (settings.value.theme === "auto") {
    isDarkTheme.value = window.matchMedia("(prefers-color-scheme: dark)").matches;
    return;
  }
  // 默认false
  isDarkTheme.value = false;
};

/**
 * 主题切换监听
 */
const themeChangeListener = () => {
  window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => {
    if (settings.value.theme === "auto") {
      isDarkTheme.value = e.matches;
    }
  });
};

/**
 * 切换主题
 * @param {string} theme - 主题名称
 */
export const changeTheme = (theme) => {
  settings.value.theme = theme;

  // 重置主题判断
  resetIsDarkTheme();
};

/**
 * 继续播放声音
 */
const playSound = async () => {
  if (audio) {
    // 如果音频对象存在，则继续播放
    await audio.play();
  } else {
    // 如果音频对象不存在，则创建并播放
    // 动态导入音频文件
    const whiteNoiseItem = whiteNoiseList.find((item) => {
      return item.name === settings.value.whiteNoise;
    });
    const audioModule = await whiteNoiseItem.audio();
    const audioPath = audioModule.default;

    audio = new Audio(audioPath);
    audio.volume = settings.value.volume / 100; // 播放音量
    audio.loop = true; // 循环播放
    await audio.play();
  }
};

/**
 * 修改时钟位置
 */
export const changeClockPasition = (x, y) => {
  // 保存时钟位置
  settings.value.clockPasitionX = x;
  settings.value.clockPasitionY = y;
};

/**
 * 暂停播放声音
 */
const pauseSound = () => {
  if (audio) {
    audio.pause();
  }
};

/**
 * 停止播放声音
 */
const stopSound = () => {
  if (audio) {
    audio.pause();
    audio = null;
  }
};

/**
 * 切换白噪音音乐
 * @param {string} name  白噪音名称
 */
export const changeWhiteNoise = (name) => {
  // 选择同一首歌，不处理
  if (name === settings.value.whiteNoise) {
    return;
  }

  // 修改并保存配置
  settings.value.whiteNoise = name;

  // 选择不同的歌，且处于播放状态
  if (settings.value.playSound) {
    //暂停上一首歌
    stopSound();
    //播放新的
    playSound();
  }
};

/**
 * 切换时钟主题
 * @param {string} theme 主题名称
 */
export const changeClockTheme = (theme) => {
  settings.value.clockTheme = theme;
};

/**
 * 调整白噪音音量
 */
export const adjustWhiteNoiseVolume = () => {
  if (audio) {
    audio.volume = settings.value.volume / 100;
  }
};

/**
 * 切换播放状态
 */
export const togglePlaySound = () => {
  // 修改并保存配置
  settings.value.playSound = !settings.value.playSound;

  // 根据配置选择播放或暂停
  if (settings.value.playSound) {
    playSound();
  } else {
    pauseSound();
  }
};

/**
 * 改变主题色
 * @param {string} color - 新的主题色值
 */
export const changeThemeColor = (color) => {
  settings.value.themeColor = color;
};

export const toggleShowClock = () => {
  //时钟管理
  if (settings.value.showClock) {
    openClock();
  } else {
    closeClock();
  }
};

/**
 * 加载配置
 */
export const loadSettings = () => {
  //开启自动保存
  autoSave();

  const DB_KEY_SETTINGS = "focus_tomato_settings";
  const data = utools.dbStorage.getItem(DB_KEY_SETTINGS);
  // 开发过程中配置经常变化，为了方便，都走默认配置，不走缓存
  const isProd = isProduction();
  if (data && isProd) {
    // 配置存在，则加载配置。如果存在新的默认配置，也会加载进去。
    // 同时解决版本更新后，新配置项丢失的问题
    settings.value = { ...defaultSettings, ...JSON.parse(data) };
  } else {
    // 配置不存在，则使用默认配置
    settings.value = { ...defaultSettings };
  }

  //主题判断
  resetIsDarkTheme();

  // 开启主题监听
  themeChangeListener();

  //加载时钟
  if (settings.value.showClock) {
    openClock();
  }
};

/**
 * 保存配置
 */
export const saveSettings = () => {
  const DB_KEY_SETTINGS = "focus_tomato_settings";
  utools.dbStorage.setItem(DB_KEY_SETTINGS, JSON.stringify(settings.value));
};

/**
 * 切换抽屉开关
 */
export const toggleDrawer = () => {
  isDrawerOpen.value = !isDrawerOpen.value;
};

/**
 * 插件退出前的操作
 */
export const beforePluginKill = () => {
  //修改播放状态
  settings.value.playSound = false;
  // 停止播放声音
  stopSound();
  // 保存配置
  saveSettings();
  // 关闭时钟
  closeClock();
};

/**
 * 监听配置变化，配置变化自动保存
 */
const autoSave = () => {
  watch(
    settings,
    () => {
      saveSettings();
    },
    // 深度监听，确保对象内部属性变化也能被监听到
    { deep: true }
  );
};
